home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 10 / AACD 10.iso / AACD / Games / MAME / src / sound / ym2151.c < prev    next >
C/C++ Source or Header  |  2000-05-22  |  55KB  |  2,086 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5. #include "driver.h"
  6. #include "ym2151.h"
  7.  
  8.  
  9. /*undef this to not use MAME timer system*/
  10. #define USE_MAME_TIMERS
  11.  
  12. /*#define FM_EMU*/
  13. #ifdef FM_EMU
  14.     #define INLINE static __inline__
  15.     #ifdef USE_MAME_TIMERS
  16.         #undef USE_MAME_TIMERS
  17.     #endif
  18. #endif
  19. #ifdef USE_MAME_TIMERS
  20.     /*#define LOG_CYM_FILE*/
  21.     #ifdef LOG_CYM_FILE
  22.         FILE * cymfile = NULL;
  23.         void * cymfiletimer = 0;
  24.     #endif
  25. #endif
  26.  
  27.  
  28. /*operator data*/
  29. typedef struct{
  30.     unsigned int phase;        /*accumulated operator phase*/
  31.     unsigned int freq;        /*operator frequency*/
  32.     signed   int DT1v;        /*operator DT1 phase inc/decrement*/
  33.  
  34.     unsigned int MUL;        /*phase multiply*/
  35.     unsigned int DT1;        /*DT1 * 32      */
  36.     unsigned int DT2;        /*DT2 index     */
  37.  
  38.     signed   int *connect;    /*operator output 'direction'*/
  39.  
  40. /*Begin of channel specific data*/
  41. /*note: each operator number 0 contains channel specific data*/
  42.     unsigned int FeedBack;    /*feedback shift value for operators 0 in each channel*/
  43.     signed   int FB;        /*operator self feedback value used only by operators 0*/
  44.     signed   int FB0;        /*previous output value*/
  45.     unsigned int KC;        /*operator KC (copied to all operators)*/
  46.     unsigned int KCindex;    /*speedup*/
  47.     unsigned int PMS;        /*channel PMS*/
  48.     unsigned int AMS;        /*channel AMS*/
  49. /*End of channel specific data*/
  50.  
  51.     unsigned int AMSmask;    /*LFO AMS enable mask*/
  52.  
  53.     unsigned int state;        /*Envelope state: 4-attack(AR) 3-decay(D1R) 2-sustain(D2R) 1-release(RR) 0-off*/
  54.     unsigned int delta_AR;    /*volume delta for attack phase*/
  55.     unsigned int TL;        /*Total attenuation Level*/
  56.     signed   int volume;    /*operator attenuation level*/
  57.     unsigned int delta_D1R;    /*volume delta for decay phase*/
  58.     unsigned int D1L;        /*EG switches to D2R, when envelope reaches this level*/
  59.     unsigned int delta_D2R;    /*volume delta for sustain phase*/
  60.     unsigned int delta_RR;    /*volume delta for release phase*/
  61.  
  62.     unsigned int key;        /*0=last key was KEY OFF, 1=last key was KEY ON*/
  63.  
  64.     unsigned int KS;        /*Key Scale     */
  65.     unsigned int AR;        /*Attack rate   */
  66.     unsigned int D1R;        /*Decay rate    */
  67.     unsigned int D2R;        /*Sustain rate  */
  68.     unsigned int RR;        /*Release rate  */
  69.  
  70.     unsigned int reserved0;    /**/
  71.     signed   int reserved1;    /**/
  72.     signed   int reserved2;    /**/
  73.  
  74. } OscilRec;
  75.  
  76.  
  77. typedef struct
  78. {
  79.     OscilRec Oscils[32];    /*there are 32 operators in YM2151*/
  80.  
  81.     unsigned int PAN[16];    /*channels output masks (0xffffffff = enable)*/
  82.  
  83.     unsigned int LFOphase;    /*accumulated LFO phase         */
  84.     unsigned int LFOfrq;    /*LFO frequency                 */
  85.     unsigned int LFOwave;    /*LFO waveform (0-saw, 1-square, 2-triangle, 3-random noise)*/
  86.     unsigned int PMD;        /*LFO Phase Modulation Depth    */
  87.     unsigned int AMD;        /*LFO Amplitude Modulation Depth*/
  88.     unsigned int LFA;        /*current AM from LFO*/
  89.     signed   int LFP;        /*current PM from LFO*/
  90.  
  91.     unsigned int test;        /*TEST register*/
  92.  
  93.     unsigned int CT;        /*output control pins (bit7 CT2, bit6 CT1)*/
  94.  
  95.     unsigned int noise;        /*noise register (bit 7 - noise enable, bits 4-0 - noise period*/
  96.     unsigned int noiseRNG;    /*17 bit noise shift register*/
  97.     unsigned int noise_p;    /*noise 'phase'*/
  98.     unsigned int noise_f;    /*noise period*/
  99.  
  100.     unsigned int CSMreq;    /*CSM KEYON/KEYOFF sequence request*/
  101.  
  102.     unsigned int IRQenable;    /*IRQ enable for timer B (bit 3) and timer A (bit 2); bit 7 - CSM mode (keyon to all slots, everytime timer A overflows)*/
  103.     unsigned int status;    /*chip status (BUSY, IRQ Flags)*/
  104.  
  105. #ifdef USE_MAME_TIMERS
  106.     void *TimATimer,*TimBTimer;    /*ASG 980324 -- added for tracking timers*/
  107.     double TimerATime[1024];    /*Timer A times for MAME*/
  108.     double TimerBTime[256];        /*Timer B times for MAME*/
  109. #else
  110.     int TimA,TimB;                /*timer A,B enable (0-disabled)*/
  111.     signed int TimAVal,TimBVal;    /*current value of timer*/
  112.     unsigned int TimerA[1024];    /*Timer A deltas*/
  113.     unsigned int TimerB[256];    /*Timer B deltas*/
  114. #endif
  115.     unsigned int TimAIndex;        /*Timer A index*/
  116.     unsigned int TimBIndex;        /*Timer B index*/
  117.  
  118.     unsigned int TimAOldIndex;    /*Timer A previous index*/
  119.     unsigned int TimBOldIndex;    /*Timer B previous index*/
  120.  
  121.     /*
  122.     *   Frequency-deltas to get the closest frequency possible.
  123.     *   There're 11 octaves because of DT2 (max 950 cents over base frequency)
  124.     *   and LFO phase modulation (max 800 cents below AND over base frequency)
  125.     *   Summary:   octave  explanation
  126.     *              0       note code - LFO PM
  127.     *              1       note code
  128.     *              2       note code
  129.     *              3       note code
  130.     *              4       note code
  131.     *              5       note code
  132.     *              6       note code
  133.     *              7       note code
  134.     *              8       note code
  135.     *              9       note code + DT2 + LFO PM
  136.     *              10      note code + DT2 + LFO PM
  137.     */
  138.     unsigned int freq[11*768];/*11 octaves, 768 'cents' per octave*/
  139.  
  140.     /*
  141.     *   Frequency deltas for DT1. These deltas alter operator frequency
  142.     *   after it has been taken from frequency-deltas table.
  143.     */
  144.     signed   int DT1freq[8*32];        /*8 DT1 levels, 32 KC values*/
  145.     unsigned int EG_tab [32+64+32];    /*Envelope Generator deltas (32 + 64 rates + 32 RKS)*/
  146.     unsigned int LFOfreq[256];        /*LFO frequency deltas*/
  147.     unsigned int noise_tab[32];        /*17bit Noise Generator periods*/
  148.  
  149.     void (*irqhandler)(int irq);    /*IRQ function handler*/
  150.     mem_write_handler porthandler;    /*port write function handler*/
  151.  
  152.     unsigned int clock;                /*chip clock in Hz (passed from 2151intf.c)*/
  153.     unsigned int sampfreq;            /*sampling frequency in Hz (passed from 2151intf.c)*/
  154.  
  155. } YM2151;
  156.  
  157.  
  158. /*
  159. **  Shifts below are subject to change when sampling frequency changes...
  160. */
  161. #define FREQ_SH            16  /* 16.16 fixed point (frequency calculations) */
  162. #define ENV_SH            16  /* 16.16 fixed point (envelope calculations)  */
  163. #define LFO_SH            23  /*  9.23 fixed point (LFO calculations)       */
  164. #define TIMER_SH        16  /* 16.16 fixed point (timers calculations)    */
  165.  
  166. #define FREQ_MASK        ((1<<FREQ_SH)-1)
  167. #define ENV_MASK        ((1<<ENV_SH)-1)
  168.  
  169. #define ENV_BITS        10
  170. #define ENV_LEN            (1<<ENV_BITS)
  171. #define ENV_STEP        (128.0/ENV_LEN)
  172. #define ENV_QUIET        ((int)(0x68/(ENV_STEP)))
  173.  
  174. #define MAX_ATT_INDEX    ((ENV_LEN<<ENV_SH)-1) /*1023.ffff*/
  175. #define MIN_ATT_INDEX    (      (1<<ENV_SH)-1) /*   0.ffff*/
  176.  
  177. #define EG_ATT            4
  178. #define EG_DEC            3
  179. #define EG_SUS            2
  180. #define EG_REL            1
  181. #define EG_OFF            0
  182.  
  183. #define SIN_BITS        10
  184. #define SIN_LEN            (1<<SIN_BITS)
  185. #define SIN_MASK        (SIN_LEN-1)
  186.  
  187. #define TL_RES_LEN        (256) /* 8 bits addressing (real chip) */
  188.  
  189. #define LFO_BITS        9
  190. #define LFO_LEN            (1<<LFO_BITS)
  191. #define LFO_MASK        (LFO_LEN-1)
  192.  
  193.  
  194. #if (SAMPLE_BITS==16)
  195.     #define FINAL_SH    (0)
  196.     #define MAXOUT        (+32767)
  197.     #define MINOUT        (-32768)
  198. #else
  199.     #define FINAL_SH    (8)
  200.     #define MAXOUT        (+127)
  201.     #define MINOUT        (-128)
  202. #endif
  203.  
  204.  
  205. /* TL_TAB_LEN is calculated as:
  206.  * 13 - sinus amplitude bits  (Y axis)
  207.  * 2  - sinus sign bit        (Y axis)
  208.  * ENV_LEN - sinus resolution (X axis)
  209. */
  210. #define TL_TAB_LEN (13*2*TL_RES_LEN)
  211. static signed int TL_TAB[TL_TAB_LEN];
  212.  
  213. /* sin waveform table in 'decibel' scale*/
  214. static unsigned int sin_tab[SIN_LEN];
  215.  
  216. /* four AM/PM LFO waveforms (8 in total)*/
  217. static unsigned int lfo_tab[LFO_LEN*4*2];
  218.  
  219. /* LFO amplitude modulation depth table (128 levels)*/
  220. static unsigned int lfo_md_tab[128];
  221.  
  222. /* translate from D1L to volume index (16 D1L levels)*/
  223. static unsigned int D1L_tab[16];
  224.  
  225. /*
  226.  *   DT2 defines offset in cents from base note
  227.  *
  228.  *   This table defines offset in frequency-deltas table.
  229.  *   User's Manual page 22
  230.  *
  231.  *   Values below were calculated using formula: value =  orig.val / 1.5625
  232.  *
  233.  *    DT2=0 DT2=1 DT2=2 DT2=3
  234.  *    0     600   781   950
  235. */
  236. static unsigned int DT2_tab[4] = { 0, 384, 500, 608 };
  237.  
  238. /*
  239.  *   DT1 defines offset in Hertz from base note
  240.  *   This table is converted while initialization...
  241.  *   Detune table in YM2151 User's Manual is wrong (checked against the real chip)
  242. */
  243.  
  244. static unsigned char DT1_tab[4*32] = { /* 4*32 DT1 values */
  245. /* DT1=0 */
  246.   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  247.   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  248.  
  249. /* DT1=1 */
  250.   0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
  251.   2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  252.  
  253. /* DT1=2 */
  254.   1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5,
  255.   5, 6, 6, 7, 8, 8, 9,10,11,12,13,14,16,16,16,16,
  256.  
  257. /* DT1=3 */
  258.   2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7,
  259.   8, 8, 9,10,11,12,13,14,16,17,19,20,22,22,22,22
  260. };
  261.  
  262. static unsigned short phaseinc_rom[768]={
  263. 1299,1300,1301,1302,1303,1304,1305,1306,1308,1309,1310,1311,1313,1314,1315,1316,
  264. 1318,1319,1320,1321,1322,1323,1324,1325,1327,1328,1329,1330,1332,1333,1334,1335,
  265. 1337,1338,1339,1340,1341,1342,1343,1344,1346,1347,1348,1349,1351,1352,1353,1354,
  266. 1356,1357,1358,1359,1361,1362,1363,1364,1366,1367,1368,1369,1371,1372,1373,1374,
  267. 1376,1377,1378,1379,1381,1382,1383,1384,1386,1387,1388,1389,1391,1392,1393,1394,
  268. 1396,1397,1398,1399,1401,1402,1403,1404,1406,1407,1408,1409,1411,1412,1413,1414,
  269. 1416,1417,1418,1419,1421,1422,1423,1424,1426,1427,1429,1430,1431,1432,1434,1435,
  270. 1437,1438,1439,1440,1442,1443,1444,1445,1447,1448,1449,1450,1452,1453,1454,1455,
  271. 1458,1459,1460,1461,1463,1464,1465,1466,1468,1469,1471,1472,1473,1474,1476,1477,
  272. 1479,1480,1481,1482,1484,1485,1486,1487,1489,1490,1492,1493,1494,1495,1497,1498,
  273. 1501,1502,1503,1504,1506,1507,1509,1510,1512,1513,1514,1515,1517,1518,1520,1521,
  274. 1523,1524,1525,1526,1528,1529,1531,1532,1534,1535,1536,1537,1539,1540,1542,1543,
  275. 1545,1546,1547,1548,1550,1551,1553,1554,1556,1557,1558,1559,1561,1562,1564,1565,
  276. 1567,1568,1569,1570,1572,1573,1575,1576,1578,1579,1580,1581,1583,1584,1586,1587,
  277. 1590,1591,1592,1593,1595,1596,1598,1599,1601,1602,1604,1605,1607,1608,1609,1610,
  278. 1613,1614,1615,1616,1618,1619,1621,1622,1624,1625,1627,1628,1630,1631,1632,1633,
  279. 1637,1638,1639,1640,1642,1643,1645,1646,1648,1649,1651,1652,1654,1655,1656,1657,
  280. 1660,1661,1663,1664,1666,1667,1669,1670,1672,1673,1675,1676,1678,1679,1681,1682,
  281. 1685,1686,1688,1689,1691,1692,1694,1695,1697,1698,1700,1701,1703,1704,1706,1707,
  282. 1709,1710,1712,1713,1715,1716,1718,1719,1721,1722,1724,1725,1727,1728,1730,1731,
  283. 1734,1735,1737,1738,1740,1741,1743,1744,1746,1748,1749,1751,1752,1754,1755,1757,
  284. 1759,1760,1762,1763,1765,1766,1768,1769,1771,1773,1774,1776,1777,1779,1780,1782,
  285. 1785,1786,1788,1789,1791,1793,1794,1796,1798,1799,1801,1802,1804,1806,1807,1809,
  286. 1811,1812,1814,1815,1817,1819,1820,1822,1824,1825,1827,1828,1830,1832,1833,1835,
  287. 1837,1838,1840,1841,1843,1845,1846,1848,1850,1851,1853,1854,1856,1858,1859,1861,
  288. 1864,1865,1867,1868,1870,1872,1873,1875,1877,1879,1880,1882,1884,1885,1887,1888,
  289. 1891,1892,1894,1895,1897,1899,1900,1902,1904,1906,1907,1909,1911,1912,1914,1915,
  290. 1918,1919,1921,1923,1925,1926,1928,1930,1932,1933,1935,1937,1939,1940,1942,1944,
  291. 1946,1947,1949,1951,1953,1954,1956,1958,1960,1961,1963,1965,1967,1968,1970,1972,
  292. 1975,1976,1978,1980,1982,1983,1985,1987,1989,1990,1992,1994,1996,1997,1999,2001,
  293. 2003,2004,2006,2008,2010,2011,2013,2015,2017,2019,2021,2022,2024,2026,2028,2029,
  294. 2032,2033,2035,2037,2039,2041,2043,2044,2047,2048,2050,2052,2054,2056,2058,2059,
  295. 2062,2063,2065,2067,2069,2071,2073,2074,2077,2078,2080,2082,2084,2086,2088,2089,
  296. 2092,2093,2095,2097,2099,2101,2103,2104,2107,2108,2110,2112,2114,2116,2118,2119,
  297. 2122,2123,2125,2127,2129,2131,2133,2134,2137,2139,2141,2142,2145,2146,2148,2150,
  298. 2153,2154,2156,2158,2160,2162,2164,2165,2168,2170,2172,2173,2176,2177,2179,2181,
  299. 2185,2186,2188,2190,2192,2194,2196,2197,2200,2202,2204,2205,2208,2209,2211,2213,
  300. 2216,2218,2220,2222,2223,2226,2227,2230,2232,2234,2236,2238,2239,2242,2243,2246,
  301. 2249,2251,2253,2255,2256,2259,2260,2263,2265,2267,2269,2271,2272,2275,2276,2279,
  302. 2281,2283,2285,2287,2288,2291,2292,2295,2297,2299,2301,2303,2304,2307,2308,2311,
  303. 2315,2317,2319,2321,2322,2325,2326,2329,2331,2333,2335,2337,2338,2341,2342,2345,
  304. 2348,2350,2352,2354,2355,2358,2359,2362,2364,2366,2368,2370,2371,2374,2375,2378,
  305. 2382,2384,2386,2388,2389,2392,2393,2396,2398,2400,2402,2404,2407,2410,2411,2414,
  306. 2417,2419,2421,2423,2424,2427,2428,2431,2433,2435,2437,2439,2442,2445,2446,2449,
  307. 2452,2454,2456,2458,2459,2462,2463,2466,2468,2470,2472,2474,2477,2480,2481,2484,
  308. 2488,2490,2492,2494,2495,2498,2499,2502,2504,2506,2508,2510,2513,2516,2517,2520,
  309. 2524,2526,2528,2530,2531,2534,2535,2538,2540,2542,2544,2546,2549,2552,2553,2556,
  310. 2561,2563,2565,2567,2568,2571,2572,2575,2577,2579,2581,2583,2586,2589,2590,2593
  311. };
  312.  
  313.  
  314.  
  315.  
  316. static YM2151 * YMPSG = NULL;    /* array of YM2151's */
  317. static unsigned int YMNumChips;    /* total # of YM2151's emulated */
  318.  
  319.  
  320. /*these variables stay here because of speedup purposes only */
  321. static YM2151 * PSG;
  322. static signed int chanout[8];
  323. static signed int c1,m2,c2; /*Phase Modulation input for operators 2,3,4*/
  324.  
  325.  
  326.  
  327. /*save output as raw 16-bit sample*/
  328. /*#define SAVE_SAMPLE*/
  329. /*#define SAVE_SEPARATE_CHANNELS*/
  330.  
  331. #if defined SAVE_SAMPLE || defined SAVE_SEPARATE_CHANNELS
  332. static FILE *sample[9];
  333. #endif
  334.  
  335.  
  336.  
  337. /* own PI definition */
  338. #ifdef PI
  339.     #undef PI
  340. #endif
  341. #define PI 3.14159265358979323846
  342.  
  343. static void init_tables(void)
  344. {
  345.     signed int i,x;
  346.     signed int n;
  347.     double o,m;
  348.  
  349.     for (x=0; x<TL_RES_LEN; x++)
  350.     {
  351.         m = (1<<16) / pow(2, (x+1) * (ENV_STEP/4.0) / 8.0);
  352.         m = floor(m);
  353.  
  354.         /* we never reach (1<<16) here due to the (x+1) */
  355.         /* result fits within 16 bits at maximum */
  356.  
  357.         n = (int)m;        /* 16 bits here */
  358.         n >>= 4;        /* 12 bits here */
  359.         if (n&1)        /* round to closest */
  360.             n = (n>>1)+1;
  361.         else
  362.             n = n>>1;
  363.                         /* 11 bits here (rounded) */
  364.         n <<= 2;        /* 13 bits here (as in real chip) */
  365.         TL_TAB[ x*2 + 0 ] = n;
  366.         TL_TAB[ x*2 + 1 ] = -TL_TAB[ x*2 + 0 ];
  367.  
  368.         for (i=1; i<13; i++)
  369.         {
  370.             TL_TAB[ x*2+0 + i*2*TL_RES_LEN ] =  TL_TAB[ x*2+0 ]>>i;
  371.             TL_TAB[ x*2+1 + i*2*TL_RES_LEN ] = -TL_TAB[ x*2+0 + i*2*TL_RES_LEN ];
  372.         }
  373.     #if 0
  374.             logerror("tl %04i", x);
  375.             for (i=0; i<13; i++)
  376.                 logerror(", [%02i] %4x", i*2, TL_TAB[ x*2 /*+1*/ + i*2*TL_RES_LEN ]);
  377.             logerror("\n");
  378.         }
  379.     #endif
  380.     }
  381.     /*logerror("TL_TAB_LEN = %i (%i bytes)\n",TL_TAB_LEN, (int)sizeof(TL_TAB));*/
  382.  
  383.  
  384.     for (i=0; i<SIN_LEN; i++)
  385.     {
  386.         /* non-standard sinus */
  387.         m = sin( ((i*2)+1) * PI / SIN_LEN ); /* checked against the real chip */
  388.  
  389.         /* we never reach zero here due to ((i*2)+1) */
  390.  
  391.         if (m>0.0)
  392.             o = 8*log(1.0/m)/log(2);  /* convert to 'decibels' */
  393.         else
  394.             o = 8*log(-1.0/m)/log(2); /* convert to 'decibels' */
  395.  
  396.         o = o / (ENV_STEP/4);
  397.  
  398.         n = (int)(2.0*o);
  399.         if (n&1)        /* round to closest */
  400.             n = (n>>1)+1;
  401.         else
  402.             n = n>>1;
  403.  
  404.         sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
  405.         /*logerror("sin [%4i]= %4i (TL_TAB value=%5i)\n", i, sin_tab[i],TL_TAB[sin_tab[i]]);*/
  406.     }
  407.  
  408.     /*logerror("ENV_QUIET= %08x\n",ENV_QUIET );*/
  409.  
  410.  
  411.     /* calculate LFO AM waveforms*/
  412.     for (x=0; x<4; x++)
  413.     {
  414.         for (i=0; i<LFO_LEN; i++)
  415.         {
  416.         switch (x)
  417.         {
  418.         case 0:    /* saw (255 down to 0) */
  419.             m = 255 - (i/2);
  420.             break;
  421.         case 1: /* square (255,0) */
  422.             if (i<256)
  423.                 m = 255;
  424.             else
  425.                 m = 0;
  426.             break;
  427.         case 2: /* triangle (255 down to 0, up to 255) */
  428.             if (i<256)
  429.                 m = 255 - i;
  430.             else
  431.                 m = i - 256;
  432.             break;
  433.         case 3: /* random (range 0 to 255) */
  434.             m = ((int)rand()) & 255;
  435.             break;
  436.         }
  437.         /* we reach m = zero here !!!*/
  438.  
  439.         if (m>0.0)
  440.             o = 8*log(255.0/m)/log(2);  /* convert to 'decibels' */
  441.         else
  442.         {
  443.             if (m<0.0)
  444.                 o = 8*log(-255.0/m)/log(2); /* convert to 'decibels' */
  445.             else
  446.                 o = 8*log(255.0/0.01)/log(2); /* small number */
  447.         }
  448.  
  449.         o = o / (ENV_STEP/4);
  450.  
  451.         n = (int)(2.0*o);
  452.         if (n&1)        /* round to closest */
  453.             n = (n>>1)+1;
  454.         else
  455.             n = n>>1;
  456.  
  457.         lfo_tab[ x*LFO_LEN*2 + i*2 ] = n*2 + (m>=0.0? 0: 1 );
  458.         /*logerror("lfo am waveofs[%i] %04i = %i\n", x, i*2, lfo_tab[ x*LFO_LEN*2 + i*2 ] );*/
  459.         }
  460.     }
  461.     for (i=0; i<128; i++)
  462.     {
  463.         m = i*2; /*m=0,2,4,6,8,10,..,252,254*/
  464.  
  465.         /* we reach m = zero here !!!*/
  466.  
  467.         if (m>0.0)
  468.             o = 8*log(8192.0/m)/log(2);  /* convert to 'decibels' */
  469.         else
  470.             o = 8*log(8192.0/0.01)/log(2); /* small number (m=0)*/
  471.  
  472.         o = o / (ENV_STEP/4);
  473.  
  474.         n = (int)(2.0*o);
  475.         if (n&1)        /* round to closest */
  476.             n = (n>>1)+1;
  477.         else
  478.             n = n>>1;
  479.  
  480.         lfo_md_tab[ i ] = n*2;
  481.         /*logerror("lfo_md_tab[%i](%i) = ofs %i shr by %i\n", i, i*2, (lfo_md_tab[i]>>1)&255, lfo_md_tab[i]>>9 );*/
  482.     }
  483.  
  484.     /* calculate LFO PM waveforms*/
  485.     for (x=0; x<4; x++)
  486.     {
  487.         for (i=0; i<LFO_LEN; i++)
  488.         {
  489.         switch (x)
  490.         {
  491.         case 0:    /* saw (0 to 127, -128 to -1) */
  492.             if (i<256)
  493.                 m = (i/2);
  494.             else
  495.                 m = (i/2)-256;
  496.             break;
  497.         case 1: /* square (127,-128) */
  498.             if (i<256)
  499.                 m = 127;
  500.             else
  501.                 m = -128;
  502.             break;
  503.         case 2: /* triangle (0 to 127,127 to -128,-127 to 0) */
  504.             if (i<128)
  505.                 m = i; /*0 to 127*/
  506.             else
  507.             {
  508.                 if (i<384)
  509.                     m = 255 - i; /*127 down to -128*/
  510.                 else
  511.                     m = i - 511; /*-127 to 0*/
  512.             }
  513.             break;
  514.         case 3: /* random (range -128 to 127) */
  515.             m = ((int)rand()) & 255;
  516.             m -=128;
  517.             break;
  518.         }
  519.         /* we reach m = zero here !!!*/
  520.  
  521.         if (m>0.0)
  522.             o = 8*log(127.0/m)/log(2);  /* convert to 'decibels' */
  523.         else
  524.         {
  525.             if (m<0.0)
  526.                 o = 8*log(-128.0/m)/log(2); /* convert to 'decibels' */
  527.             else
  528.                 o = 8*log(127.0/0.01)/log(2); /* small number */
  529.         }
  530.  
  531.         o = o / (ENV_STEP/4);
  532.  
  533.         n = (int)(2.0*o);
  534.         if (n&1)        /* round to closest */
  535.             n = (n>>1)+1;
  536.         else
  537.             n = n>>1;
  538.  
  539.         lfo_tab[ x*LFO_LEN*2 + i*2 + 1 ] = n*2 + (m>=0.0? 0: 1 );
  540.         /*logerror("lfo pm waveofs[%i] %04i = %i\n", x, i*2+1, lfo_tab[ x*LFO_LEN*2 + i*2 + 1 ] );*/
  541.         }
  542.     }
  543.  
  544.     /* calculate D1L_tab table */
  545.     for (i=0; i<16; i++)
  546.     {
  547.         m = (i!=15 ? i : i+16) * (4.0/ENV_STEP);   /*every 3 'dB' except for all bits = 1 = 45dB+48dB*/
  548.         D1L_tab[i] = m * (1<<ENV_SH);
  549.         /*logerror("D1L_tab[%02x]=%08x\n",i,D1L_tab[i] );*/
  550.     }
  551.  
  552. #ifdef SAVE_SAMPLE
  553. sample[8]=fopen("sampsum.raw","ab");
  554. #endif
  555. #ifdef SAVE_SEPARATE_CHANNELS
  556. sample[0]=fopen("samp0.raw","wb");
  557. sample[1]=fopen("samp1.raw","wb");
  558. sample[2]=fopen("samp2.raw","wb");
  559. sample[3]=fopen("samp3.raw","wb");
  560. sample[4]=fopen("samp4.raw","wb");
  561. sample[5]=fopen("samp5.raw","wb");
  562. sample[6]=fopen("samp6.raw","wb");
  563. sample[7]=fopen("samp7.raw","wb");
  564. #endif
  565. }
  566.  
  567. static void init_chip_tables(YM2151 *chip)
  568. {
  569.     int i,j;
  570.     double mult,pom,pom2,clk,phaseinc,Hz;
  571.  
  572.     double scaler;    /* formula below is true for chip clock=3579545 */
  573.     /* so we need to scale its output accordingly to the chip clock */
  574.  
  575.     /*scaler = (double)chip->clock / 3579545.0;*/
  576.     scaler = ( (double)chip->clock / 64.0 ) / ( (double)chip->sampfreq );
  577. #if 0
  578.     logerror("scaler    = %20.15f\n", scaler);
  579.     logerror("scalerold = %20.15f\n", (double)chip->clock / 3579545.0 );
  580. #endif
  581.  
  582.     /*this loop calculates Hertz values for notes from c-0 to b-7*/
  583.     /*including 64 'cents' (100/64 that is 1.5625 of real cent) per note*/
  584.     /* i*100/64/1200 is equal to i/768 */
  585.  
  586.     /* real chip works with 10 bits fixed point values (10.10)*/
  587.     mult = (1<<(FREQ_SH-10)); /* -10 because phaseinc_rom table values are already in 10.10 format */
  588.  
  589.     for (i=0; i<768; i++)
  590.     {
  591.         /* 3.4375 Hz is note A; C# is 4 semitones higher */
  592.         Hz = 1000;
  593. #if 0
  594. /* Hz is close, but not perfect */
  595.         //Hz = scaler * 3.4375 * pow (2, (i + 4 * 64 ) / 768.0 );
  596.         /* calculate phase increment */
  597.         phaseinc = (Hz*SIN_LEN) / (double)chip->sampfreq;
  598. #endif
  599.  
  600.         phaseinc = phaseinc_rom[i];    /*real chip phase increment*/
  601.         phaseinc *= scaler;            /*adjust*/
  602.  
  603.  
  604.         /*octave 2 - reference octave*/
  605.         chip->freq[ 768+2*768+i ] = ((int)(phaseinc*mult)) & 0xffffffc0; /*adjust to X.10 fixed point*/
  606.  
  607.         /*octave 0 and octave 1*/
  608.         for (j=0; j<2; j++)
  609.         {
  610.             chip->freq[768 + j*768 + i] = (chip->freq[ 768+2*768+i ] >> (2-j) ) & 0xffffffc0; /*adjust to X.10 fixed point*/
  611.         }
  612.  
  613.         /*octave 3 to 7*/
  614.         for (j=3; j<8; j++)
  615.         {
  616.             chip->freq[768 + j*768 + i] = chip->freq[ 768+2*768+i ] << (j-2);
  617.         }
  618.  
  619.     #if 0
  620.             pom = (double)chip->freq[ 768+2*768+i ] / ((double)(1<<FREQ_SH));
  621.             pom = pom * (double)chip->sampfreq / (double)SIN_LEN;
  622.             logerror("1freq[%4i][%08x]= real %20.15f Hz  emul %20.15f Hz\n", i, chip->freq[ 768+2*768+i ], Hz, pom);
  623.     #endif
  624.     }
  625.  
  626.     /*octave -1 (all equal to: oct 0, KC 00, KF 00) */
  627.     for (i=0; i<768; i++)
  628.     {
  629.         chip->freq[ 0*768 + i ] = chip->freq[1*768+0];
  630.     }
  631.  
  632.     /*octave 8 and 9 (all equal to: oct 7, _KC_14_, _KF_63_) */
  633.     for (j=8; j<10; j++)
  634.     {
  635.         for (i=0; i<768; i++)
  636.         {
  637.             chip->freq[768+ j*768 + i ] = chip->freq[768 + 8*768 -1];
  638.         }
  639.     }
  640.  
  641.     #if 0
  642.         for (i=0; i<11*768; i++)
  643.         {
  644.             pom = (double)chip->freq[i] / ((double)(1<<FREQ_SH));
  645.             pom = pom * (double)chip->sampfreq / (double)SIN_LEN;
  646.             logerror("freq[%4i][%08x]= emul %20.15f Hz\n", i, chip->freq[i], pom);
  647.         }
  648.     #endif
  649.  
  650.     mult = (1<<FREQ_SH);
  651.     for (j=0; j<4; j++)
  652.     {
  653.         for (i=0; i<32; i++)
  654.         {
  655.             Hz = ( (double)DT1_tab[j*32+i] * ((double)chip->clock/64.0) ) / (double)(1<<20);
  656.  
  657.             /*calculate phase increment*/
  658.             phaseinc = (Hz*SIN_LEN) / (double)chip->sampfreq;
  659.  
  660.             /*positive and negative values*/
  661.             chip->DT1freq[ (j+0)*32 + i ] = phaseinc * mult;
  662.             chip->DT1freq[ (j+4)*32 + i ] = -chip->DT1freq[ (j+0)*32 + i ];
  663.  
  664.         #if 0
  665.             {
  666.                 int x = j*32 + i;
  667.                 pom = (double)chip->DT1freq[x] / mult;
  668.                 pom = pom * (double)chip->sampfreq / (double)SIN_LEN;
  669.                 logerror("DT1(%03i)[%02i %02i][%08x]= real %19.15f Hz  emul %19.15f Hz\n",
  670.                          x, j, i, chip->DT1freq[x], Hz, pom);
  671.             }
  672.         #endif
  673.         }
  674.     }
  675.  
  676.     mult = (1<<LFO_SH);
  677.     clk  = (double)chip->clock;
  678.     for (i=0; i<256; i++)
  679.     {
  680.         j = i & 0x0f;
  681.         pom = fabs(  (clk/65536/(1<<(i/16)) ) - (clk/65536/32/(1<<(i/16)) * (j+1)) );
  682.  
  683.         /*calculate phase increment*/
  684.         chip->LFOfreq[0xff-i] = ( (pom*LFO_LEN) / (double)chip->sampfreq ) * mult; /*fixed point*/
  685.         /*logerror("LFO[%02x] (%08x)= real %20.15f Hz  emul %20.15f Hz\n",0xff-i, chip->LFOfreq[0xff-i], pom,
  686.             (((double)chip->LFOfreq[0xff-i] / mult) * (double)chip->sampfreq ) / (double)LFO_LEN );*/
  687.     }
  688.  
  689.     for (i=0; i<34; i++)
  690.         chip->EG_tab[i] = 0;        /* infinity */
  691.  
  692.     for (i=2; i<64; i++)
  693.     {
  694.         pom2 = (double)chip->clock / (double)chip->sampfreq;
  695.         if (i<60) pom2 *= ( 1 + (i&3)*0.25 );
  696.         pom2 *= 1<<((i>>2));
  697.         pom2 /= 768.0 * 1024.0;
  698.         pom2 *= (double)(1<<ENV_SH);
  699.         chip->EG_tab[32+i] = pom2;
  700.     #if 0
  701.         logerror("Rate %2i %1i  Decay [real %11.4f ms][emul %11.4f ms][d=%08x]\n",i>>2, i&3,
  702.             ( ((double)(ENV_LEN<<ENV_SH)) / pom2 )                       * (1000.0 / (double)chip->sampfreq),
  703.             ( ((double)(ENV_LEN<<ENV_SH)) / (double)chip->EG_tab[32+i] ) * (1000.0 / (double)chip->sampfreq), chip->EG_tab[32+i] );
  704.     #endif
  705.     }
  706.  
  707.     for (i=0; i<32; i++)
  708.     {
  709.         chip->EG_tab[ 32+64+i ] = chip->EG_tab[32+63];
  710.     }
  711.  
  712.     /* precalculate timers' deltas */
  713.     /* User's Manual pages 15,16  */
  714.     mult = (1<<TIMER_SH);
  715.     for (i=0; i<1024; i++)
  716.     {
  717.         /* ASG 980324: changed to compute both TimerA and TimerATime */
  718.         pom= ( 64.0  *  (1024.0-i) / (double)chip->clock );
  719.         #ifdef USE_MAME_TIMERS
  720.             chip->TimerATime[i] = pom;
  721.         #else
  722.             chip->TimerA[i] = pom * (double)chip->sampfreq * mult;  /*number of samples that timer period takes (fixed point) */
  723.         #endif
  724.     }
  725.     for (i=0; i<256; i++)
  726.     {
  727.         /* ASG 980324: changed to compute both TimerB and TimerBTime */
  728.         pom= ( 1024.0 * (256.0-i)  / (double)chip->clock );
  729.         #ifdef USE_MAME_TIMERS
  730.             chip->TimerBTime[i] = pom;
  731.         #else
  732.             chip->TimerB[i] = pom * (double)chip->sampfreq * mult;  /*number of samples that timer period takes (fixed point) */
  733.         #endif
  734.     }
  735.  
  736.     /* calculate noise periods table */
  737.     scaler = ( (double)chip->clock / 64.0 ) / ( (double)chip->sampfreq );
  738.     for (i=0; i<32; i++)
  739.     {
  740.         j = (i!=31 ? i : 30);   /*period 30 and 31 are the same*/
  741.         j = 32-j;
  742.         j = (65536.0 / (double)(j*32.0));    /*number of samples per one shift of the shift register*/
  743.         /*chip->noise_tab[i] = j * 64;*/    /*number of chip clock cycles per one shift*/
  744.         chip->noise_tab[i] = j * 64 * scaler;
  745.         /*logerror("noise_tab[%02x]=%08x\n", i, chip->noise_tab[i]);*/
  746.     }
  747.  
  748. }
  749.  
  750.  
  751. /*#define RESET_FEEDBACK_ON_KEYON*/
  752.  
  753. INLINE void envelope_KONKOFF(OscilRec * op, int v)
  754. {
  755.     if (v&0x08)
  756.     {
  757.         if (!op->key)
  758.         {
  759.             op->key   = 1;      /*KEYON'ed*/
  760.             op->phase = 0;      /*clear phase */
  761.             op->state = EG_ATT; /*KEY ON = attack*/
  762.         }
  763.     }
  764.     else
  765.     {
  766.         if (op->key)
  767.         {
  768.             op->key   = 0;      /*KEYOFF'ed*/
  769.             if (op->state>EG_REL)
  770.                 op->state = EG_REL; /*release*/
  771.         }
  772.     }
  773.  
  774.     op+=8;
  775.  
  776.     if (v&0x20)
  777.     {
  778.         if (!op->key)
  779.         {
  780.             op->key   = 1;
  781.             op->phase = 0;
  782.             op->state = EG_ATT;
  783.         }
  784.     }
  785.     else
  786.     {
  787.         if (op->key)
  788.         {
  789.             op->key   = 0;
  790.             if (op->state>EG_REL)
  791.                 op->state = EG_REL;
  792.         }
  793.     }
  794.  
  795.     op+=8;
  796.  
  797.     if (v&0x10)
  798.     {
  799.         if (!op->key)
  800.         {
  801.             op->key   = 1;
  802.             op->phase = 0;
  803.             op->state = EG_ATT;
  804.         }
  805.     }
  806.     else
  807.     {
  808.         if (op->key)
  809.         {
  810.             op->key   = 0;
  811.             if (op->state>EG_REL)
  812.                 op->state = EG_REL;
  813.         }
  814.     }
  815.  
  816.     op+=8;
  817.  
  818.     if (v&0x40)
  819.     {
  820.         if (!op->key)
  821.         {
  822.             op->key   = 1;
  823.             op->phase = 0;
  824.             op->state = EG_ATT;
  825.         }
  826.     }
  827.     else
  828.     {
  829.         if (op->key)
  830.         {
  831.             op->key   = 0;
  832.             if (op->state>EG_REL)
  833.                 op->state = EG_REL;
  834.         }
  835.     }
  836. }
  837.  
  838.  
  839. #ifdef USE_MAME_TIMERS
  840. static void timer_callback_a (int n)
  841. {
  842.     YM2151 *chip = &YMPSG[n];
  843.     chip->TimATimer = timer_set (chip->TimerATime[ chip->TimAIndex ], n, timer_callback_a);
  844.     chip->TimAOldIndex = chip->TimAIndex;
  845.     if (chip->IRQenable & 0x04)
  846.     {
  847.         int oldstate = chip->status & 3;
  848.         chip->status |= 1;
  849.         if ((!oldstate) && (chip->irqhandler)) (*chip->irqhandler)(1);
  850.     }
  851.     if (chip->IRQenable & 0x80)
  852.         chip->CSMreq = 2;    /*request KEYON/KEYOFF sequence*/
  853. }
  854. static void timer_callback_b (int n)
  855. {
  856.     YM2151 *chip = &YMPSG[n];
  857.     chip->TimBTimer = timer_set (chip->TimerBTime[ chip->TimBIndex ], n, timer_callback_b);
  858.     chip->TimBOldIndex = chip->TimBIndex;
  859.     if (chip->IRQenable & 0x08)
  860.     {
  861.         int oldstate = chip->status & 3;
  862.         chip->status |= 2;
  863.         if ((!oldstate) && (chip->irqhandler)) (*chip->irqhandler)(1);
  864.     }
  865. }
  866. #if 0
  867. static void timer_callback_chip_write_busy (int n)
  868. {
  869.     YM2151 *chip = &YMPSG[n];
  870.     chip->status &= 0x7f;    /*reset busy flag*/
  871. }
  872. #endif
  873. #endif
  874.  
  875.  
  876. INLINE void set_connect( OscilRec *om1, int v, int cha)
  877. {
  878.     OscilRec *om2 = om1+8;
  879.     OscilRec *oc1 = om1+16;
  880.     /*OscilRec *oc2 = om1+24;*/
  881.     /*oc2->connect = &chanout[cha];*/
  882.  
  883.     /* set connect algorithm */
  884.  
  885.     switch( v & 7 )
  886.     {
  887.     case 0:
  888.         /* M1---C1---M2---C2---OUT */
  889.         om1->connect = &c1;
  890.         oc1->connect = &m2;
  891.         om2->connect = &c2;
  892.         break;
  893.     case 1:
  894.         /* M1-+-M2---C2---OUT */
  895.         /* C1-+               */
  896.         om1->connect = &m2;
  897.         oc1->connect = &m2;
  898.         om2->connect = &c2;
  899.         break;
  900.     case 2:
  901.         /* M1------+-C2---OUT */
  902.         /* C1---M2-+          */
  903.         om1->connect = &c2;
  904.         oc1->connect = &m2;
  905.         om2->connect = &c2;
  906.         break;
  907.     case 3:
  908.         /* M1---C1-+-C2---OUT */
  909.         /* M2------+          */
  910.         om1->connect = &c1;
  911.         oc1->connect = &c2;
  912.         om2->connect = &c2;
  913.         break;
  914.     case 4:
  915.         /* M1---C1-+--OUT */
  916.         /* M2---C2-+      */
  917.         om1->connect = &c1;
  918.         oc1->connect = &chanout[cha];
  919.         om2->connect = &c2;
  920.         break;
  921.     case 5:
  922.         /*    +-C1-+     */
  923.         /* M1-+-M2-+-OUT */
  924.         /*    +-C2-+     */
  925.         om1->connect = 0;    /* special mark */
  926.         oc1->connect = &chanout[cha];
  927.         om2->connect = &chanout[cha];
  928.         break;
  929.     case 6:
  930.         /* M1---C1-+     */
  931.         /*      M2-+-OUT */
  932.         /*      C2-+     */
  933.         om1->connect = &c1;
  934.         oc1->connect = &chanout[cha];
  935.         om2->connect = &chanout[cha];
  936.         break;
  937.     case 7:
  938.         /* M1-+     */
  939.         /* C1-+-OUT */
  940.         /* M2-+     */
  941.         /* C2-+     */
  942.         om1->connect = &chanout[cha];
  943.         oc1->connect = &chanout[cha];
  944.         om2->connect = &chanout[cha];
  945.         break;
  946.     }
  947. }
  948.  
  949.  
  950. INLINE void refresh_EG( YM2151 *chip, OscilRec * op)
  951. {
  952.     unsigned int kc;
  953.     unsigned int v;
  954.  
  955.     kc = op->KC;
  956.  
  957.     /*v = 32 + 2*RATE + RKS (max 126)*/
  958.  
  959.     v = kc >> op->KS;
  960.     if ((op->AR+v) < 32+62)
  961.         op->delta_AR  = chip->EG_tab[ op->AR + v];
  962.     else
  963.         op->delta_AR  = MAX_ATT_INDEX+1;
  964.     op->delta_D1R = chip->EG_tab[op->D1R + v];
  965.     op->delta_D2R = chip->EG_tab[op->D2R + v];
  966.     op->delta_RR  = chip->EG_tab[ op->RR + v];
  967.  
  968.     op+=8;
  969.  
  970.     v = kc >> op->KS;
  971.     if ((op->AR+v) < 32+62)
  972.         op->delta_AR  = chip->EG_tab[ op->AR + v];
  973.     else
  974.         op->delta_AR  = MAX_ATT_INDEX+1;
  975.     op->delta_D1R = chip->EG_tab[op->D1R + v];
  976.     op->delta_D2R = chip->EG_tab[op->D2R + v];
  977.     op->delta_RR  = chip->EG_tab[ op->RR + v];
  978.  
  979.     op+=8;
  980.  
  981.     v = kc >> op->KS;
  982.     if ((op->AR+v) < 32+62)
  983.         op->delta_AR  = chip->EG_tab[ op->AR + v];
  984.     else
  985.         op->delta_AR  = MAX_ATT_INDEX+1;
  986.     op->delta_D1R = chip->EG_tab[op->D1R + v];
  987.     op->delta_D2R = chip->EG_tab[op->D2R + v];
  988.     op->delta_RR  = chip->EG_tab[ op->RR + v];
  989.  
  990.     op+=8;
  991.  
  992.     v = kc >> op->KS;
  993.     if ((op->AR+v) < 32+62)
  994.         op->delta_AR  = chip->EG_tab[ op->AR + v];
  995.     else
  996.         op->delta_AR  = MAX_ATT_INDEX+1;
  997.     op->delta_D1R = chip->EG_tab[op->D1R + v];
  998.     op->delta_D2R = chip->EG_tab[op->D2R + v];
  999.     op->delta_RR  = chip->EG_tab[ op->RR + v];
  1000.  
  1001. }
  1002.  
  1003.  
  1004. /* write a register on YM2151 chip number 'n' */
  1005. void YM2151WriteReg(int n, int r, int v)
  1006. {
  1007.     YM2151 *chip = &(YMPSG[n]);
  1008.     OscilRec *op = &chip->Oscils[ r&0x1f ];
  1009.  
  1010.     /*adjust bus to 8 bits*/
  1011.     r &= 0xff;
  1012.     v &= 0xff;
  1013.  
  1014. #if 0
  1015.     /*There's no info on what YM2151 really does when busy flag is set*/
  1016.     if ( chip->status & 0x80 ) return;
  1017.     timer_set ( 68.0 / (double)chip->clock, n, timer_callback_chip_write_busy);
  1018.     chip->status |= 0x80;    /* set busy flag for 68 chip clock cycles */
  1019. #endif
  1020.  
  1021. #ifdef LOG_CYM_FILE
  1022.     if ((cymfile) && (r!=0) )
  1023.     {
  1024.         fputc( (unsigned char)r, cymfile );
  1025.         fputc( (unsigned char)v, cymfile );
  1026.     }
  1027. #endif
  1028.  
  1029.  
  1030.     switch(r & 0xe0){
  1031.     case 0x00:
  1032.         switch(r){
  1033.         case 0x01: /*LFO reset(bit 1), Test Register (other bits)*/
  1034.             chip->test = v;
  1035.             if (v&2) chip->LFOphase = 0;
  1036.             break;
  1037.  
  1038.         case 0x08:
  1039.             envelope_KONKOFF(&chip->Oscils[ v&7 ], v );
  1040.             break;
  1041.  
  1042.         case 0x0f: /*noise mode enable, noise period*/
  1043.             chip->noise = v;
  1044.             chip->noise_f = chip->noise_tab[ v & 0x1f ];
  1045.             #if 0
  1046.             if (v){
  1047.                 usrintf_showmessage("YM2151 noise mode = %02x",v);
  1048.                 logerror("YM2151 noise (%02x)\n",v);
  1049.             }
  1050.             #endif
  1051.             break;
  1052.  
  1053.         case 0x10: /*timer A hi*/
  1054.             chip->TimAIndex = (chip->TimAIndex & 0x003) | (v<<2);
  1055.             break;
  1056.  
  1057.         case 0x11: /*timer A low*/
  1058.             chip->TimAIndex = (chip->TimAIndex & 0x3fc) | (v & 3);
  1059.             break;
  1060.  
  1061.         case 0x12: /*timer B*/
  1062.             chip->TimBIndex = v;
  1063.             break;
  1064.  
  1065.         case 0x14: /*CSM, irq flag reset, irq enable, timer start/stop*/
  1066.  
  1067.             chip->IRQenable = v;    /*bit 3-timer B, bit 2-timer A, bit 7 - CSM */
  1068.  
  1069.             if (v&0x20)    /*reset timer B irq flag*/
  1070.             {
  1071.                 int oldstate = chip->status & 3;
  1072.                 chip->status &= 0xfd;
  1073.                 if ((oldstate==2) && (chip->irqhandler)) (*chip->irqhandler)(0);
  1074.             }
  1075.  
  1076.             if (v&0x10)    /*reset timer A irq flag*/
  1077.             {
  1078.                 int oldstate = chip->status & 3;
  1079.                 chip->status &= 0xfe;
  1080.                 if ((oldstate==1) && (chip->irqhandler)) (*chip->irqhandler)(0);
  1081.  
  1082.             }
  1083.  
  1084.             if (v&0x02){    /*load and start timer B*/
  1085.                 #ifdef USE_MAME_TIMERS
  1086.                 /* ASG 980324: added a real timer */
  1087.                 /* start timer _only_ if it wasn't already started (it will reload time value next round)*/
  1088.                     if (!chip->TimBTimer)
  1089.                     {
  1090.                         chip->TimBTimer = timer_set (chip->TimerBTime[ chip->TimBIndex ], n, timer_callback_b);
  1091.                         chip->TimBOldIndex = chip->TimBIndex;
  1092.                     }
  1093.                     #if 1
  1094.                     else
  1095.                     {
  1096.                         /*check if timer value has changed since last start and update if necessary*/
  1097.                         if (chip->TimBIndex!=chip->TimBOldIndex)
  1098.                         {
  1099.                             double timepassed = timer_timeelapsed(chip->TimBTimer);
  1100.                             timer_remove (chip->TimBTimer);
  1101.                             chip->TimBTimer = timer_set (chip->TimerBTime[ chip->TimBIndex ] - timepassed, n, timer_callback_b);
  1102.                             chip->TimBOldIndex = chip->TimBIndex;
  1103.                         }
  1104.                     }
  1105.                     #endif
  1106.                 #else
  1107.                     if (!chip->TimB)
  1108.                     {
  1109.                         chip->TimB = 1;
  1110.                         chip->TimBVal = chip->TimerB[ chip->TimBIndex ];
  1111.                     }
  1112.                 #endif
  1113.             }else{        /*stop timer B*/
  1114.                 #ifdef USE_MAME_TIMERS
  1115.                 /* ASG 980324: added a real timer */
  1116.                     if (chip->TimBTimer) timer_remove (chip->TimBTimer);
  1117.                     chip->TimBTimer = 0;
  1118.                 #else
  1119.                     chip->TimB = 0;
  1120.                 #endif
  1121.             }
  1122.  
  1123.             if (v&0x01){    /*load and start timer A*/
  1124.                 #ifdef USE_MAME_TIMERS
  1125.                 /* ASG 980324: added a real timer */
  1126.                 /* start timer _only_ if it wasn't already started (it will reload time value next round)*/
  1127.                     if (!chip->TimATimer)
  1128.                     {
  1129.                         chip->TimATimer = timer_set (chip->TimerATime[ chip->TimAIndex ], n, timer_callback_a);
  1130.                         chip->TimAOldIndex = chip->TimAIndex;
  1131.                     }
  1132.                     #if 1
  1133.                     else
  1134.                     {
  1135.                         /*check if timer value has changed since last start and update if necessary*/
  1136.                         if (chip->TimAIndex!=chip->TimAOldIndex)
  1137.                         {
  1138.                             double timepassed = timer_timeelapsed(chip->TimATimer);
  1139.                             timer_remove (chip->TimATimer);
  1140.                             chip->TimATimer = timer_set (chip->TimerATime[ chip->TimAIndex ] - timepassed, n, timer_callback_a);
  1141.                             chip->TimAOldIndex = chip->TimAIndex;
  1142.                         }
  1143.                     }
  1144.                     #endif
  1145.                 #else
  1146.                     if (!chip->TimA)
  1147.                     {
  1148.                         chip->TimA = 1;
  1149.                         chip->TimAVal = chip->TimerA[ chip->TimAIndex ];
  1150.                     }
  1151.                 #endif
  1152.             }else{        /*stop timer A*/
  1153.                 #ifdef USE_MAME_TIMERS
  1154.                 /* ASG 980324: added a real timer */
  1155.                     if (chip->TimATimer) timer_remove (chip->TimATimer);
  1156.                     chip->TimATimer = 0;
  1157.                 #else
  1158.                     chip->TimA = 0;
  1159.                 #endif
  1160.             }
  1161.             break;
  1162.  
  1163.         case 0x18: /*LFO frequency*/
  1164.             chip->LFOfrq = chip->LFOfreq[ v ];
  1165.             break;
  1166.  
  1167.         case 0x19: /*PMD (bit 7==1) or AMD (bit 7==0)*/
  1168.             if (v&0x80)
  1169.                 chip->PMD = lfo_md_tab[ v&0x7f ] + 512;
  1170.             else
  1171.                 chip->AMD = lfo_md_tab[ v&0x7f ];
  1172.             break;
  1173.  
  1174.         case 0x1b: /*CT2, CT1, LFO waveform*/
  1175.             chip->CT = v;
  1176.             chip->LFOwave = (v & 3) * LFO_LEN*2;
  1177.             if (chip->porthandler) (*chip->porthandler)(0 , (chip->CT) >> 6 );
  1178.             break;
  1179.  
  1180.         default:
  1181.             logerror("YM2151 Write %02x to undocumented register #%02x\n",v,r);
  1182.             break;
  1183.         }
  1184.         break;
  1185.  
  1186.     case 0x20:
  1187.         op = &chip->Oscils[r & 7];
  1188.         switch(r & 0x18){
  1189.         case 0x00: /*RL enable, Feedback, Connection */
  1190.             op->FeedBack = ((v>>3)&7) ? ((v>>3)&7)+6:0;
  1191.             chip->PAN[ (r&7)*2    ] = (v & 0x40) ? 0xffffffff : 0x0;
  1192.             chip->PAN[ (r&7)*2 +1 ] = (v & 0x80) ? 0xffffffff : 0x0;
  1193.             set_connect(op, v, r&7);
  1194.             break;
  1195.  
  1196.         case 0x08: /*Key Code*/
  1197.             v &= 0x7f;
  1198.             if (v != op->KC)
  1199.             {
  1200.                 unsigned int kc, kc_channel;
  1201.  
  1202.                 kc_channel = (v - (v>>2))*64;
  1203.                 kc_channel += 768;
  1204.                 kc_channel |= (op->KCindex & 63);
  1205.  
  1206.                 (op+ 0)->KC = v;
  1207.                 (op+ 0)->KCindex = kc_channel;
  1208.                 (op+ 8)->KC = v;
  1209.                 (op+ 8)->KCindex = kc_channel;
  1210.                 (op+16)->KC = v;
  1211.                 (op+16)->KCindex = kc_channel;
  1212.                 (op+24)->KC = v;
  1213.                 (op+24)->KCindex = kc_channel;
  1214.  
  1215.                 kc = v>>2;
  1216.  
  1217.                 (op+ 0)->DT1v = chip->DT1freq[ (op+ 0)->DT1 + kc ];
  1218.                 (op+ 0)->freq = ( (chip->freq[ kc_channel + (op+ 0)->DT2 ] + (op+ 0)->DT1v) * (op+ 0)->MUL ) >> 1;
  1219.  
  1220.                 (op+ 8)->DT1v = chip->DT1freq[ (op+ 8)->DT1 + kc ];
  1221.                 (op+ 8)->freq = ( (chip->freq[ kc_channel + (op+ 8)->DT2 ] + (op+ 8)->DT1v) * (op+ 8)->MUL ) >> 1;
  1222.  
  1223.                 (op+16)->DT1v = chip->DT1freq[ (op+16)->DT1 + kc ];
  1224.                 (op+16)->freq = ( (chip->freq[ kc_channel + (op+16)->DT2 ] + (op+16)->DT1v) * (op+16)->MUL ) >> 1;
  1225.  
  1226.                 (op+24)->DT1v = chip->DT1freq[ (op+24)->DT1 + kc ];
  1227.                 (op+24)->freq = ( (chip->freq[ kc_channel + (op+24)->DT2 ] + (op+24)->DT1v) * (op+24)->MUL ) >> 1;
  1228.  
  1229.                 refresh_EG( chip, op );
  1230.             }
  1231.             break;
  1232.  
  1233.         case 0x10: /*Key Fraction*/
  1234.             v >>= 2;
  1235.             if (v !=  (op->KCindex & 63))
  1236.             {
  1237.                 unsigned int kc_channel;
  1238.  
  1239.                 kc_channel = v;
  1240.                 kc_channel |= (op->KCindex & ~63);
  1241.  
  1242.                 (op+ 0)->KCindex = kc_channel;
  1243.                 (op+ 8)->KCindex = kc_channel;
  1244.                 (op+16)->KCindex = kc_channel;
  1245.                 (op+24)->KCindex = kc_channel;
  1246.  
  1247.                 (op+ 0)->freq = ( (chip->freq[ kc_channel + (op+ 0)->DT2 ] + (op+ 0)->DT1v) * (op+ 0)->MUL ) >> 1;
  1248.                 (op+ 8)->freq = ( (chip->freq[ kc_channel + (op+ 8)->DT2 ] + (op+ 8)->DT1v) * (op+ 8)->MUL ) >> 1;
  1249.                 (op+16)->freq = ( (chip->freq[ kc_channel + (op+16)->DT2 ] + (op+16)->DT1v) * (op+16)->MUL ) >> 1;
  1250.                 (op+24)->freq = ( (chip->freq[ kc_channel + (op+24)->DT2 ] + (op+24)->DT1v) * (op+24)->MUL ) >> 1;
  1251.             }
  1252.             break;
  1253.  
  1254.         case 0x18: /*PMS,AMS*/
  1255.             op->PMS = (v>>4) & 7;
  1256.             op->AMS = v & 3;
  1257.             break;
  1258.         }
  1259.         break;
  1260.  
  1261.     case 0x40: /*DT1, MUL*/
  1262.         {
  1263.             unsigned int oldDT1 = op->DT1;
  1264.             unsigned int oldMUL = op->MUL;
  1265.             op->DT1 = (v&0x70)<<1;
  1266.             op->MUL = (v&0x0f) ? (v&0x0f)<<1: 1;
  1267.             if (oldDT1 != op->DT1)
  1268.             {
  1269.                 op->DT1v = chip->DT1freq[ op->DT1 + (op->KC>>2) ];
  1270.             }
  1271.             if ( (oldDT1 != op->DT1) || (oldMUL != op->MUL) )
  1272.             {
  1273.                 op->freq = ( (chip->freq[ op->KCindex + op->DT2 ] + op->DT1v) * op->MUL ) >> 1;
  1274.             }
  1275.         }
  1276.         break;
  1277.  
  1278.     case 0x60: /*TL*/
  1279.         op->TL = (v&0x7f)<<(ENV_BITS-7); /*7bit TL*/
  1280.         break;
  1281.  
  1282.     case 0x80: /*KS, AR*/
  1283.         {
  1284.             int oldKS = op->KS;
  1285.             int oldAR = op->AR;
  1286.             op->KS = 5-(v>>6);
  1287.             op->AR = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
  1288.  
  1289.             if ( (op->AR != oldAR) || (op->KS != oldKS) )
  1290.             {
  1291.                 if ((op->AR + (op->KC>>op->KS)) < 32+62)
  1292.                     op->delta_AR  = chip->EG_tab[op->AR  + (op->KC>>op->KS) ];
  1293.                 else
  1294.                     op->delta_AR  = MAX_ATT_INDEX+1;
  1295.             }
  1296.  
  1297.             if (op->KS != oldKS)
  1298.             {
  1299.                 op->delta_D1R = chip->EG_tab[op->D1R + (op->KC>>op->KS) ];
  1300.                 op->delta_D2R = chip->EG_tab[op->D2R + (op->KC>>op->KS) ];
  1301.                 op->delta_RR  = chip->EG_tab[op->RR  + (op->KC>>op->KS) ];
  1302.             }
  1303.         }
  1304.         break;
  1305.  
  1306.     case 0xa0: /*AMS-EN, D1R*/
  1307.         op->AMSmask = (v&0x80) ? 0xffffffff : 0;
  1308.         op->D1R     = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
  1309.         op->delta_D1R = chip->EG_tab[op->D1R + (op->KC>>op->KS) ];
  1310.         break;
  1311.  
  1312.     case 0xc0: /*DT2, D2R*/
  1313.         {
  1314.             unsigned int oldDT2 = op->DT2;
  1315.             op->DT2 = DT2_tab[ v>>6 ];
  1316.             if (op->DT2 != oldDT2)
  1317.             {
  1318.                 op->freq = ( (chip->freq[ op->KCindex + op->DT2 ] + op->DT1v) * op->MUL ) >> 1;
  1319.             }
  1320.         }
  1321.         op->D2R = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
  1322.         op->delta_D2R = chip->EG_tab[op->D2R + (op->KC>>op->KS) ];
  1323.         break;
  1324.  
  1325.     case 0xe0: /*D1L, RR*/
  1326.         op->D1L = D1L_tab[ v>>4 ];
  1327.         op->RR  = 34 + ((v&0x0f)<<2);
  1328.         op->delta_RR  = chip->EG_tab[op->RR  + (op->KC>>op->KS) ];
  1329.         break;
  1330.     }
  1331. }
  1332.  
  1333.  
  1334. #ifdef LOG_CYM_FILE
  1335. static void cymfile_callback (int n)
  1336. {
  1337.     if (cymfile)
  1338.     {
  1339.         fputc( (unsigned char)0, cymfile );
  1340.     }
  1341. }
  1342. #endif
  1343.  
  1344.  
  1345. int YM2151ReadStatus( int n )
  1346. {
  1347.     return YMPSG[n].status;
  1348. }
  1349.  
  1350.  
  1351. /*
  1352. ** Initialize YM2151 emulator(s).
  1353. **
  1354. ** 'num' is the number of virtual YM2151's to allocate
  1355. ** 'clock' is the chip clock in Hz
  1356. ** 'rate' is sampling rate
  1357. */
  1358. int YM2151Init(int num, int clock, int rate)
  1359. {
  1360.     int i;
  1361.  
  1362.     if (YMPSG) return (-1);    /* duplicate init. */
  1363.  
  1364.     YMNumChips = num;
  1365.  
  1366.     YMPSG = (YM2151 *)malloc(sizeof(YM2151) * YMNumChips);
  1367.     if (YMPSG == NULL) return (1);
  1368.  
  1369.     memset(YMPSG, 0, sizeof(YM2151) * YMNumChips);
  1370.  
  1371. #if 0
  1372.     TL_TAB = (signed int *)malloc(sizeof(signed int) * TL_TAB_LEN );
  1373.     if (TL_TAB == NULL)
  1374.     {
  1375.         free(YMPSG);
  1376.         YMPSG=NULL;
  1377.         return (1);
  1378.     }
  1379. #endif
  1380.  
  1381.     init_tables();
  1382.     for (i=0 ; i<YMNumChips; i++)
  1383.     {
  1384.         YMPSG[i].clock = clock;
  1385.         /*rate = clock/64;*/
  1386.         YMPSG[i].sampfreq = rate ? rate : 44100;    /* avoid division by 0 in init_chip_tables() */
  1387.         YMPSG[i].irqhandler = NULL;                    /*interrupt handler */
  1388.         YMPSG[i].porthandler = NULL;                /*port write handler*/
  1389.         init_chip_tables(&YMPSG[i]);
  1390. #ifdef USE_MAME_TIMERS
  1391. /*this must be done _before_ a call to YM2151ResetChip() */
  1392.         YMPSG[i].TimATimer = 0;
  1393.         YMPSG[i].TimBTimer = 0;
  1394. #else
  1395.         YMPSG[i].TimA      = 0;
  1396.         YMPSG[i].TimB      = 0;
  1397. #endif
  1398.         YM2151ResetChip(i);
  1399.         /*logerror("YM2151[init] clock=%i sampfreq=%i\n", YMPSG[i].clock, YMPSG[i].sampfreq);*/
  1400.     }
  1401.  
  1402. #ifdef LOG_CYM_FILE
  1403.     cymfile = fopen("2151_.cym","wb");
  1404.     if (cymfile)
  1405.         cymfiletimer = timer_pulse ( TIME_IN_HZ(110), 0, cymfile_callback); /*110 Hz pulse timer*/
  1406.     else
  1407.         logerror("Could not create file 2151_.cym\n");
  1408. #endif
  1409.  
  1410.     return(0);
  1411. }
  1412.  
  1413. void YM2151Shutdown()
  1414. {
  1415.     if (!YMPSG) return;
  1416.  
  1417.     free(YMPSG);
  1418.     YMPSG = NULL;
  1419. #if 0
  1420.     if (TL_TAB)
  1421.     {
  1422.         free(TL_TAB);
  1423.         TL_TAB=NULL;
  1424.     }
  1425. #endif
  1426.  
  1427.  
  1428. #ifdef LOG_CYM_FILE
  1429.     fclose(cymfile);
  1430.     cymfile = NULL;
  1431.     if (cymfiletimer) timer_remove (cymfiletimer);
  1432.     cymfiletimer = 0;
  1433. #endif
  1434.  
  1435. #ifdef SAVE_SAMPLE
  1436.     fclose(sample[8]);
  1437. #endif
  1438. #ifdef SAVE_SEPARATE_CHANNELS
  1439.     fclose(sample[0]);
  1440.     fclose(sample[1]);
  1441.     fclose(sample[2]);
  1442.     fclose(sample[3]);
  1443.     fclose(sample[4]);
  1444.     fclose(sample[5]);
  1445.     fclose(sample[6]);
  1446.     fclose(sample[7]);
  1447. #endif
  1448. }
  1449.  
  1450.  
  1451. /*
  1452. ** reset all chip registers.
  1453. */
  1454. void YM2151ResetChip(int num)
  1455. {
  1456.     int i;
  1457.     YM2151 *chip = &YMPSG[num];
  1458.  
  1459.     /* initialize hardware registers */
  1460.  
  1461.     for (i=0; i<32; i++)
  1462.     {
  1463.         memset(&chip->Oscils[i],'\0',sizeof(OscilRec));
  1464.         chip->Oscils[i].volume = MAX_ATT_INDEX;
  1465.     }
  1466.  
  1467.     chip->LFOphase = 0;
  1468.     chip->LFOfrq   = 0;
  1469.     chip->LFOwave  = 0;
  1470.     chip->PMD = lfo_md_tab[ 0 ] + 512;
  1471.     chip->AMD = lfo_md_tab[ 0 ];
  1472.     chip->LFA = 0;
  1473.     chip->LFP = 0;
  1474.  
  1475.     chip->test= 0;
  1476.  
  1477.     chip->IRQenable = 0;
  1478. #ifdef USE_MAME_TIMERS
  1479.     /* ASG 980324 -- reset the timers before writing to the registers */
  1480.     if (chip->TimATimer) timer_remove (chip->TimATimer);
  1481.     chip->TimATimer = 0;
  1482.     if (chip->TimBTimer) timer_remove (chip->TimBTimer);
  1483.     chip->TimBTimer = 0;
  1484. #else
  1485.     chip->TimA      = 0;
  1486.     chip->TimB      = 0;
  1487.     chip->TimAVal   = 0;
  1488.     chip->TimBVal   = 0;
  1489. #endif
  1490.     chip->TimAIndex = 0;
  1491.     chip->TimBIndex = 0;
  1492.     chip->TimAOldIndex = 0;
  1493.     chip->TimBOldIndex = 0;
  1494.  
  1495.     chip->noise     = 0;
  1496.     chip->noiseRNG  = 0;
  1497.     chip->noise_p   = 0;
  1498.     chip->noise_f   = chip->noise_tab[0];
  1499.  
  1500.     chip->CSMreq    = 0;
  1501.  
  1502.     chip->status    = 0;
  1503.  
  1504.     YM2151WriteReg(num, 0x1b, 0); /*only because of CT1, CT2 output pins*/
  1505.     for (i=0x20; i<0x100; i++)   /*just to set the PM operators */
  1506.     {
  1507.         YM2151WriteReg(num, i, 0);
  1508.     }
  1509.  
  1510. }
  1511.  
  1512.  
  1513. INLINE void lfo_calc(void)
  1514. {
  1515. unsigned int phase, lfx;
  1516.  
  1517.     if (PSG->test&2)
  1518.     {
  1519.         PSG->LFOphase = 0;
  1520.         phase = PSG->LFOwave;
  1521.     }
  1522.     else
  1523.     {
  1524.         phase = (PSG->LFOphase>>LFO_SH) & LFO_MASK;
  1525.         phase = phase*2 + PSG->LFOwave;
  1526.     }
  1527.  
  1528.     lfx = lfo_tab[phase] + PSG->AMD;
  1529.  
  1530.     PSG->LFA = 0;
  1531.     if (lfx < TL_TAB_LEN)
  1532.         PSG->LFA = TL_TAB[ lfx ];
  1533.  
  1534.     lfx = lfo_tab[phase+1] + PSG->PMD;
  1535.  
  1536.     PSG->LFP = 0;
  1537.     if (lfx < TL_TAB_LEN)
  1538.         PSG->LFP = TL_TAB[ lfx ];
  1539. }
  1540.  
  1541.  
  1542. INLINE void calc_lfo_pm(OscilRec *op)
  1543. {
  1544. signed int mod_ind, pom;
  1545.  
  1546.     mod_ind = PSG->LFP; /* -128..+127 (8bits signed)*/
  1547.     if (op->PMS < 6)
  1548.         mod_ind >>= (6 - op->PMS);
  1549.     else
  1550.         mod_ind <<= (op->PMS - 5);
  1551.  
  1552.     if (mod_ind)
  1553.     {
  1554.         unsigned int kc_channel;
  1555.  
  1556.         kc_channel = op->KCindex + mod_ind;
  1557.  
  1558.         pom = ( (PSG->freq[ kc_channel + op->DT2 ] + op->DT1v) * op->MUL ) >> 1;
  1559.         op->phase += (pom - op->freq);
  1560.  
  1561.         op+=8;
  1562.         pom = ( (PSG->freq[ kc_channel + op->DT2 ] + op->DT1v) * op->MUL ) >> 1;
  1563.         op->phase += (pom - op->freq);
  1564.  
  1565.         op+=8;
  1566.         pom = ( (PSG->freq[ kc_channel + op->DT2 ] + op->DT1v) * op->MUL ) >> 1;
  1567.         op->phase += (pom - op->freq);
  1568.  
  1569.         op+=8;
  1570.         pom = ( (PSG->freq[ kc_channel + op->DT2 ] + op->DT1v) * op->MUL ) >> 1;
  1571.         op->phase += (pom - op->freq);
  1572.     }
  1573. }
  1574.  
  1575.  
  1576. INLINE signed int op_calc(OscilRec * OP, unsigned int env, signed int pm)
  1577. {
  1578.     unsigned int p;
  1579.  
  1580.     p = (env<<3) + sin_tab[ ( ((signed int)((OP->phase & ~FREQ_MASK) + (pm<<15))) >> FREQ_SH ) & SIN_MASK ];
  1581.  
  1582.     if (p >= TL_TAB_LEN)
  1583.         return 0;
  1584.  
  1585.     return TL_TAB[p];
  1586. }
  1587.  
  1588. INLINE signed int op_calc1(OscilRec * OP, unsigned int env, signed int pm)
  1589. {
  1590.     unsigned int p;
  1591.     signed int i;
  1592.  
  1593.     i = (OP->phase & ~FREQ_MASK) + pm;
  1594.  
  1595. /*logerror("i=%08x (i>>16)&511=%8i phase=%i [pm=%08x] ",i, (i>>16)&511, OP->phase>>FREQ_SH, pm);*/
  1596.  
  1597.     p = (env<<3) + sin_tab[ (i>>FREQ_SH) & SIN_MASK];
  1598.  
  1599. /*logerror("(p&255=%i p>>8=%i) out= %i\n", p&255,p>>8, TL_TAB[p&255]>>(p>>8) );*/
  1600.  
  1601.     if (p >= TL_TAB_LEN)
  1602.         return 0;
  1603.  
  1604.     return TL_TAB[p];
  1605. }
  1606.  
  1607.  
  1608. #define volume_calc(OP) (OP->TL + (((unsigned int)OP->volume)>>ENV_SH) + (AM & OP->AMSmask))
  1609.  
  1610. INLINE void chan_calc(unsigned int chan)
  1611. {
  1612. OscilRec *OP;
  1613. unsigned int env;
  1614. unsigned int AM;
  1615.  
  1616.     chanout[chan]= c1 = m2 = c2 = 0;
  1617.     AM = 0;
  1618.  
  1619.     OP = &PSG->Oscils[chan]; /*M1*/
  1620.  
  1621.     if (OP->AMS)
  1622.         AM = PSG->LFA << (OP->AMS-1);
  1623.  
  1624.     if (OP->PMS)
  1625.         calc_lfo_pm(OP);
  1626.  
  1627.     env = volume_calc(OP);
  1628.     {
  1629.         signed int out;
  1630.  
  1631.         out = OP->FB0 + OP->FB;
  1632.         OP->FB0 = OP->FB;
  1633.  
  1634.         if (!OP->connect)
  1635.             /* algorithm 5 */
  1636.             c1 = m2 = c2 = OP->FB0;
  1637.         else
  1638.             /* other algorithms */
  1639.             *OP->connect = OP->FB0;
  1640.  
  1641.         OP->FB = 0;
  1642.  
  1643.         if (env < ENV_QUIET)
  1644.             OP->FB = op_calc1(OP, env, (out<<OP->FeedBack) );
  1645.     }
  1646.  
  1647.     OP += 16; /*C1*/
  1648.     env = volume_calc(OP);
  1649.     if (env < ENV_QUIET)
  1650.         *OP->connect += op_calc(OP, env, c1);
  1651.  
  1652.     OP -= 8;  /*M2*/
  1653.     env = volume_calc(OP);
  1654.     if (env < ENV_QUIET)
  1655.         *OP->connect += op_calc(OP, env, m2);
  1656.  
  1657.     OP += 16; /*C2*/
  1658.     env = volume_calc(OP);
  1659.     if (env < ENV_QUIET)
  1660.         chanout[chan] += op_calc(OP, env, c2);
  1661.  
  1662. }
  1663. INLINE void chan7_calc(void)
  1664. {
  1665. OscilRec *OP;
  1666. unsigned int env;
  1667. unsigned int AM;
  1668.  
  1669.     chanout[7]= c1 = m2 = c2 = 0;
  1670.     AM = 0;
  1671.  
  1672.     OP = &PSG->Oscils[7]; /*M1*/
  1673.  
  1674.     if (OP->AMS)
  1675.         AM = PSG->LFA << (OP->AMS-1);
  1676.  
  1677.     if (OP->PMS)
  1678.         calc_lfo_pm(OP);
  1679.  
  1680.     env = volume_calc(OP);
  1681.     {
  1682.         signed int out;
  1683.  
  1684.         out = OP->FB0 + OP->FB;
  1685.         OP->FB0 = OP->FB;
  1686.  
  1687.         if (!OP->connect)
  1688.             /* algorithm 5 */
  1689.             c1 = m2 = c2 = OP->FB0;
  1690.         else
  1691.             /* other algorithms */
  1692.             *OP->connect = OP->FB0;
  1693.  
  1694.         OP->FB = 0;
  1695.  
  1696.         if (env < ENV_QUIET)
  1697.             OP->FB = op_calc1(OP, env, (out<<OP->FeedBack) );
  1698.     }
  1699.  
  1700.     OP += 16; /*C1*/
  1701.     env = volume_calc(OP);
  1702.     if (env < ENV_QUIET)
  1703.         *OP->connect += op_calc(OP, env, c1);
  1704.  
  1705.     OP -= 8;  /*M2*/
  1706.     env = volume_calc(OP);
  1707.     if (env < ENV_QUIET)
  1708.         *OP->connect += op_calc(OP, env, m2);
  1709.  
  1710.     OP += 16; /*C2*/
  1711.     env = volume_calc(OP);
  1712.  
  1713.     if (PSG->noise & 0x80)
  1714.     {
  1715.         unsigned int noiseout;
  1716.  
  1717.         noiseout = 0;
  1718.         if (env < 0x3ff)
  1719.             noiseout = (env ^ 0x3ff) * 2; /*range of the YM2151 noise output is -2044 to 2040*/
  1720.         chanout[7] += ((PSG->noiseRNG&0x10000) ? noiseout: -noiseout); /*bit 16 -> output*/
  1721.     }
  1722.     else
  1723.     {
  1724.         if (env < ENV_QUIET)
  1725.             chanout[7] += op_calc(OP, env, c2);
  1726.     }
  1727.  
  1728. }
  1729.  
  1730. INLINE void advance(void)
  1731. {
  1732. OscilRec *op;
  1733. int i;
  1734.  
  1735.     if (!(PSG->test&2))
  1736.         PSG->LFOphase += PSG->LFOfrq;
  1737.  
  1738.     /* The Noise Generator of the YM2151 is 17-bit shift register.
  1739.     ** Input to the bit16 is negated (bit0 XOR bit3) (EXNOR).
  1740.     ** Output of the register is negated (bit0 XOR bit3).
  1741.     ** Simply use bit16 as the noise output.
  1742.     */
  1743.     PSG->noise_p += PSG->noise_f;
  1744.     i = (PSG->noise_p>>16);        /*number of events (shifts of the shift register)*/
  1745.     PSG->noise_p &= 0xffff;
  1746.     while (i)
  1747.     {
  1748.         unsigned int j;
  1749.         j = ( (PSG->noiseRNG ^ (PSG->noiseRNG>>3) ) & 1) ^ 1;
  1750.         PSG->noiseRNG = (j<<16) | (PSG->noiseRNG>>1);
  1751.         i--;
  1752.     }
  1753.  
  1754.     /* In real it seems that CSM keyon line is ORed with the KO line inside of the chip.
  1755.     ** This causes it to only work when KO is off, ie. 0
  1756.     ** Below is my implementation only.
  1757.     */
  1758.     if (PSG->CSMreq) /*CSM KEYON/KEYOFF seqeunce request*/
  1759.     {
  1760.         if (PSG->CSMreq==2)    /*KEYON*/
  1761.         {
  1762.             op = &PSG->Oscils[0]; /*CH 0 M1*/
  1763.             i = 32;
  1764.             do
  1765.             {
  1766.                 if (op->key==0) /*_ONLY_ when KEY is OFF (checked)*/
  1767.                 {
  1768.                     op->phase = 0;
  1769.                     op->state = EG_ATT;
  1770.                 }
  1771.                 op++;
  1772.                 i--;
  1773.             }while (i);
  1774.             PSG->CSMreq = 1;
  1775.         }
  1776.         else                    /*KEYOFF*/
  1777.         {
  1778.             op = &PSG->Oscils[0]; /*CH 0 M1*/
  1779.             i = 32;
  1780.             do
  1781.             {
  1782.                 if (op->key==0) /*_ONLY_ when KEY is OFF (checked)*/
  1783.                 {
  1784.                     if (op->state>EG_REL)
  1785.                         op->state = EG_REL;
  1786.                 }
  1787.                 op++;
  1788.                 i--;
  1789.             }while (i);
  1790.             PSG->CSMreq = 0;
  1791.         }
  1792.     }
  1793.  
  1794.     op = &PSG->Oscils[0]; /*CH0 M1*/
  1795.     i = 32;
  1796.     do
  1797.     {
  1798.         op->phase += op->freq;
  1799.  
  1800.         switch(op->state)
  1801.         {
  1802.         case EG_ATT:    /*attack phase*/
  1803.         {
  1804.             signed int step;
  1805.  
  1806.             step = op->volume;
  1807.             op->volume -= op->delta_AR;
  1808.             step = (step>>ENV_SH) - (((unsigned int)op->volume)>>ENV_SH); /*number of levels passed since last time*/
  1809.             if (step > 0)
  1810.             {
  1811.                 signed int tmp_volume;
  1812.  
  1813.                 tmp_volume = op->volume + (step<<ENV_SH); /*adjust by number of levels*/
  1814.                 do
  1815.                 {
  1816.                     tmp_volume = tmp_volume - (1<<ENV_SH) - ((tmp_volume>>4) & ~ENV_MASK);
  1817.                     if (tmp_volume <= MIN_ATT_INDEX)
  1818.                         break;
  1819.                     step--;
  1820.                 }while(step);
  1821.                 op->volume = tmp_volume;
  1822.             }
  1823.  
  1824.             if (op->volume <= MIN_ATT_INDEX)
  1825.             {
  1826.                 if (op->volume < 0)
  1827.                     op->volume = 0; /*this is not quite correct (checked)*/
  1828.                 op->state = EG_DEC;
  1829.             }
  1830.         }
  1831.         break;
  1832.  
  1833.         case EG_DEC:    /*decay phase*/
  1834.             if ( (op->volume += op->delta_D1R) >= op->D1L )
  1835.             {
  1836.                 op->volume = op->D1L; /*this is not quite correct (checked)*/
  1837.                 op->state = EG_SUS;
  1838.             }
  1839.         break;
  1840.  
  1841.         case EG_SUS:    /*sustain phase*/
  1842.             if ( (op->volume += op->delta_D2R) > MAX_ATT_INDEX )
  1843.             {
  1844.                 op->state = EG_OFF;
  1845.                 op->volume = MAX_ATT_INDEX;
  1846.             }
  1847.         break;
  1848.  
  1849.         case EG_REL:    /*release phase*/
  1850.             if ( (op->volume += op->delta_RR) > MAX_ATT_INDEX )
  1851.             {
  1852.                 op->state = EG_OFF;
  1853.                 op->volume = MAX_ATT_INDEX;
  1854.             }
  1855.         break;
  1856.         }
  1857.         op++;
  1858.         i--;
  1859.     }while (i);
  1860. }
  1861.  
  1862. #if 0
  1863. INLINE signed int acc_calc(signed int value)
  1864. {
  1865.     if (value>=0)
  1866.     {
  1867.         if (value < 0x0200)
  1868.             return (value);
  1869.         if (value < 0x0400)
  1870.             return (value & 0xfffffffe);
  1871.         if (value < 0x0800)
  1872.             return (value & 0xfffffffc);
  1873.         if (value < 0x1000)
  1874.             return (value & 0xfffffff8);
  1875.         if (value < 0x2000)
  1876.             return (value & 0xfffffff0);
  1877.         if (value < 0x4000)
  1878.             return (value & 0xffffffe0);
  1879.         return (value & 0xffffffc0);
  1880.     }
  1881.     /*else value < 0*/
  1882.     if (value > -0x0200)
  1883.         return (value);
  1884.     if (value > -0x0400)
  1885.         return (value & 0xfffffffe);
  1886.     if (value > -0x0800)
  1887.         return (value & 0xfffffffc);
  1888.     if (value > -0x1000)
  1889.         return (value & 0xfffffff8);
  1890.     if (value > -0x2000)
  1891.         return (value & 0xfffffff0);
  1892.     if (value > -0x4000)
  1893.         return (value & 0xffffffe0);
  1894.     return (value & 0xffffffc0);
  1895.  
  1896. }
  1897. #endif
  1898.  
  1899. /*first macro saves left and right channels to mono file*/
  1900. /*second macro saves left and right channels to stereo file*/
  1901. #if 0    /*MONO*/
  1902.     #ifdef SAVE_SEPARATE_CHANNELS
  1903.       #define SAVE_SINGLE_CHANNEL(j) \
  1904.       {    signed int pom= -(chanout[j] & PSG->PAN[j*2]); \
  1905.         if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
  1906.         fputc((unsigned short)pom&0xff,sample[j]); \
  1907.         fputc(((unsigned short)pom>>8)&0xff,sample[j]);  }
  1908.     #else
  1909.       #define SAVE_SINGLE_CHANNEL(j)
  1910.     #endif
  1911. #else    /*STEREO*/
  1912.     #ifdef SAVE_SEPARATE_CHANNELS
  1913.       #define SAVE_SINGLE_CHANNEL(j) \
  1914.       {    signed int pom = -(chanout[j] & PSG->PAN[j*2]); \
  1915.         if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
  1916.         fputc((unsigned short)pom&0xff,sample[j]); \
  1917.         fputc(((unsigned short)pom>>8)&0xff,sample[j]); \
  1918.         pom = -(chanout[j] & PSG->PAN[j*2+1]); \
  1919.         if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
  1920.         fputc((unsigned short)pom&0xff,sample[j]); \
  1921.         fputc(((unsigned short)pom>>8)&0xff,sample[j]); \
  1922.       }
  1923.     #else
  1924.       #define SAVE_SINGLE_CHANNEL(j)
  1925.     #endif
  1926. #endif
  1927.  
  1928. /*first macro saves left and right channels to mono file*/
  1929. /*second macro saves left and right channels to stereo file*/
  1930. #if 1    /*MONO*/
  1931.     #ifdef SAVE_SAMPLE
  1932.       #define SAVE_ALL_CHANNELS \
  1933.       {    signed int pom = outr; \
  1934.         pom >>= FINAL_SH; \
  1935.         if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
  1936.         /*pom = acc_calc(pom);*/ \
  1937.         /*fprintf(sample[8]," %i\n",pom);*/ \
  1938.         fputc((unsigned short)pom&0xff,sample[8]); \
  1939.         fputc(((unsigned short)pom>>8)&0xff,sample[8]); \
  1940.       }
  1941.     #else
  1942.       #define SAVE_ALL_CHANNELS
  1943.     #endif
  1944. #else    /*STEREO*/
  1945.     #ifdef SAVE_SAMPLE
  1946.       #define SAVE_ALL_CHANNELS \
  1947.       {    signed int pom = outl; \
  1948.         pom >>= FINAL_SH; \
  1949.         if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
  1950.         fputc((unsigned short)pom&0xff,sample[8]); \
  1951.         fputc(((unsigned short)pom>>8)&0xff,sample[8]); \
  1952.         pom = outr; \
  1953.         pom >>= FINAL_SH; \
  1954.         if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
  1955.         fputc((unsigned short)pom&0xff,sample[8]); \
  1956.         fputc(((unsigned short)pom>>8)&0xff,sample[8]); \
  1957.       }
  1958.     #else
  1959.       #define SAVE_ALL_CHANNELS
  1960.     #endif
  1961. #endif
  1962.  
  1963.  
  1964. /*
  1965. ** Generate samples for one of the YM2151's
  1966. **
  1967. ** 'num' is the number of virtual YM2151
  1968. ** '**buffers' is table of pointers to the buffers: left and right
  1969. ** 'length' is the number of samples that should be generated
  1970. */
  1971. void YM2151UpdateOne(int num, INT16 **buffers, int length)
  1972. {
  1973.     int i;
  1974.     signed int outl,outr;
  1975.     SAMP *bufL, *bufR;
  1976.  
  1977.     bufL = buffers[0];
  1978.     bufR = buffers[1];
  1979.  
  1980.     PSG = &YMPSG[num];
  1981.  
  1982.     #ifdef USE_MAME_TIMERS
  1983.         /* ASG 980324 - handled by real timers now */
  1984.     #else
  1985.     if (PSG->TimB)
  1986.     {
  1987.         PSG->TimBVal -= ( length << TIMER_SH );
  1988.         if (PSG->TimBVal<=0)
  1989.         {
  1990.             PSG->TimBVal += PSG->TimerB[ PSG->TimBIndex ];
  1991.             if ( PSG->IRQenable & 0x08 )
  1992.             {
  1993.                 int oldstate = PSG->status & 3;
  1994.                 PSG->status |= 2;
  1995.                 if ((!oldstate) && (PSG->irqhandler)) (*PSG->irqhandler)(1);
  1996.             }
  1997.         }
  1998.     }
  1999.     #endif
  2000.  
  2001.     for (i=0; i<length; i++)
  2002.     {
  2003.  
  2004.         chan_calc(0);
  2005.         SAVE_SINGLE_CHANNEL(0)
  2006.         chan_calc(1);
  2007.         SAVE_SINGLE_CHANNEL(1)
  2008.         chan_calc(2);
  2009.         SAVE_SINGLE_CHANNEL(2)
  2010.         chan_calc(3);
  2011.         SAVE_SINGLE_CHANNEL(3)
  2012.         chan_calc(4);
  2013.         SAVE_SINGLE_CHANNEL(4)
  2014.         chan_calc(5);
  2015.         SAVE_SINGLE_CHANNEL(5)
  2016.         chan_calc(6);
  2017.         SAVE_SINGLE_CHANNEL(6)
  2018.         chan7_calc();
  2019.         SAVE_SINGLE_CHANNEL(7)
  2020.  
  2021.         SAVE_ALL_CHANNELS
  2022.  
  2023.         outl = chanout[0] & PSG->PAN[0];
  2024.         outr = chanout[0] & PSG->PAN[1];
  2025.         outl += (chanout[1] & PSG->PAN[2]);
  2026.         outr += (chanout[1] & PSG->PAN[3]);
  2027.         outl += (chanout[2] & PSG->PAN[4]);
  2028.         outr += (chanout[2] & PSG->PAN[5]);
  2029.         outl += (chanout[3] & PSG->PAN[6]);
  2030.         outr += (chanout[3] & PSG->PAN[7]);
  2031.         outl += (chanout[4] & PSG->PAN[8]);
  2032.         outr += (chanout[4] & PSG->PAN[9]);
  2033.         outl += (chanout[5] & PSG->PAN[10]);
  2034.         outr += (chanout[5] & PSG->PAN[11]);
  2035.         outl += (chanout[6] & PSG->PAN[12]);
  2036.         outr += (chanout[6] & PSG->PAN[13]);
  2037.         outl += (chanout[7] & PSG->PAN[14]);
  2038.         outr += (chanout[7] & PSG->PAN[15]);
  2039.  
  2040.         outl >>= FINAL_SH;
  2041.         outr >>= FINAL_SH;
  2042.         if (outl > MAXOUT) outl = MAXOUT;
  2043.             else if (outl < MINOUT) outl = MINOUT;
  2044.         if (outr > MAXOUT) outr = MAXOUT;
  2045.             else if (outr < MINOUT) outr = MINOUT;
  2046.         ((SAMP*)bufL)[i] = (SAMP)outl;
  2047.         ((SAMP*)bufR)[i] = (SAMP)outr;
  2048.  
  2049.         #ifdef USE_MAME_TIMERS
  2050.         /* ASG 980324 - handled by real timers now */
  2051.         #else
  2052.         /* calculate timer A */
  2053.         if (PSG->TimA)
  2054.         {
  2055.             PSG->TimAVal -= ( 1 << TIMER_SH );
  2056.             if (PSG->TimAVal <= 0)
  2057.             {
  2058.                 PSG->TimAVal += PSG->TimerA[ PSG->TimAIndex ];
  2059.                 if (PSG->IRQenable & 0x04)
  2060.                 {
  2061.                     int oldstate = PSG->status & 3;
  2062.                     PSG->status |= 1;
  2063.                     if ((!oldstate) && (PSG->irqhandler)) (*PSG->irqhandler)(1);
  2064.                 }
  2065.                 if (PSG->IRQenable & 0x80)
  2066.                     PSG->CSMreq = 2; /*request KEYON/KEYOFF sequence*/
  2067.             }
  2068.         }
  2069.         #endif
  2070.  
  2071.         lfo_calc();
  2072.         advance();
  2073.     }
  2074. }
  2075.  
  2076. void YM2151SetIrqHandler(int n, void(*handler)(int irq))
  2077. {
  2078.     YMPSG[n].irqhandler = handler;
  2079. }
  2080.  
  2081. void YM2151SetPortWriteHandler(int n, mem_write_handler handler)
  2082. {
  2083.     YMPSG[n].porthandler = handler;
  2084. }
  2085.  
  2086.